package com.example.nettydemo.codec.marshalling;

import com.example.nettydemo.codec.ptotobuf.SubscibeReqProto;
import com.example.nettydemo.codec.ptotobuf.SubscibeRespProto;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MarshallingSubReqServerHandler extends ChannelHandlerAdapter {

    private int counter;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscibeReq req = (SubscibeReq) msg;
        log.info("request: [{}], counter: [{}]", req.toString(), ++counter);

        ctx.writeAndFlush(initSubscibeResp(req));
    }

    private SubscibeResp initSubscibeResp(SubscibeReq req){
        SubscibeResp resp = new SubscibeResp();
        resp.setSubReqID(req.getSubReqID());
        resp.setRespCode(200);
        resp.setDesc("成功");

        return resp;
    }
}
